<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>主动报工-会员中心 - 工厂报工系统</title>
{include file="common/header"}

<div class="max-w-lg mx-auto bg-white rounded shadow p-6 mt-8">
  <h2 class="text-xl font-bold mb-4 text-blue-600">主动报工</h2>
  
  {if condition="$error"}
    <div class="mb-4 p-3 bg-red-100 text-red-700 rounded text-center text-base font-bold">{$error}</div>
  {/if}
  {if condition="$success"}
    <div class="mb-4 p-3 bg-green-100 text-green-700 rounded text-center text-base font-bold">{$success}</div>
  {/if}
  
  <form method="post" class="space-y-4" id="activeReportForm">
    <div>
      <label class="block mb-1 font-medium">选择订单</label>
      <select name="order_id" class="w-full border rounded px-3 py-2" id="order-select" required>
        <option value="">请选择订单</option>
        {volist name="orders" id="order"}
        <option value="{$order.id}">{$order.order_no} - {$order.customer_name}</option>
        {/volist}
      </select>
    </div>
    
    <div>
      <label class="block mb-1 font-medium">选择产品型号和工序</label>
      <select name="order_model" class="w-full border rounded px-3 py-2" id="order-model-select" required>
        <option value="">请先选择订单</option>
      </select>
      <div class="mt-2 p-3 bg-blue-50 border border-blue-200 rounded" id="price-info" style="display:none;">
        <div class="text-sm">
          <div>计件单价：<span class="font-bold text-blue-600" id="piece-price">0</span> 元/件</div>
          <div>计时单价：<span class="font-bold text-blue-600" id="time-price">0</span> 元/小时</div>
        </div>
      </div>
    </div>
    
    <!-- 订单信息显示 -->
    <div class="mb-4 p-4 bg-gray-50 rounded" id="order-info" style="display:none;">
      <div class="text-sm text-gray-800 mb-1">订单总量：<span class="font-bold" id="total-quantity">0</span></div>
      <div class="text-sm text-gray-800 mb-1">已分配数量：<span class="font-bold" id="allocated-quantity">0</span></div>
      <div class="text-sm text-gray-800">可报工数量：<span class="font-bold text-primary" id="available-quantity">0</span></div>
    </div>
    
    <div>
      <label class="block mb-1 font-medium">报工类型</label>
      <div class="flex space-x-4">
        <label class="flex items-center">
          <input type="radio" name="report_type" value="piece" checked class="mr-2">
          <span>计件报工</span>
        </label>
        <label class="flex items-center">
          <input type="radio" name="report_type" value="time" class="mr-2">
          <span>计时报工</span>
        </label>
      </div>
    </div>
    
    <div id="piece-section">
      <label class="block mb-1 font-medium">报工数量</label>
      <input type="number" name="quantity" class="w-full border rounded px-3 py-2" id="quantity-input" placeholder="请输入报工数量" min="1" required>
      <p class="text-xs text-gray-500 mt-1">最大可报工数量：<span id="max-quantity">0</span></p>
    </div>
    
    <div id="time-section" style="display:none;">
      <label class="block mb-1 font-medium">工作时长</label>
      <input type="number" name="work_hours" class="w-full border rounded px-3 py-2" id="work-hours-input" placeholder="直接填写工作时长（小时）" step="0.5" min="0">
      <p class="text-xs text-gray-500 mt-1">或者填写开始和结束时间</p>
    </div>
    
    <div id="time-range-section" style="display:none;">
      <label class="block mb-1 font-medium">工作时间</label>
      <div class="flex space-x-2">
        <input type="time" name="start_time" class="flex-1 border rounded px-3 py-2" id="start-time" placeholder="开始时间">
        <span class="flex items-center">到</span>
        <input type="time" name="end_time" class="flex-1 border rounded px-3 py-2" id="end-time" placeholder="结束时间">
      </div>
      <div class="mt-2 p-3 bg-blue-50 border border-blue-200 rounded" id="time-calculator" style="display:none;">
        <div class="text-center font-bold text-blue-600">
          计算工作时长：<span id="calculated-hours">0</span> 小时
        </div>
      </div>
    </div>
    
    <div>
      <label class="block mb-1 font-medium">工作日期</label>
      <input type="date" name="work_date" class="w-full border rounded px-3 py-2" value="{:date('Y-m-d')}" required>
    </div>
    
    <div>
      <label class="block mb-1 font-medium">备注</label>
      <textarea name="remark" class="w-full border rounded px-3 py-2" rows="3" placeholder="请输入备注信息"></textarea>
    </div>
    
    <button type="submit" class="w-full bg-blue-600 text-white py-2 rounded font-bold hover:bg-blue-700">
      <i class="fa fa-save mr-2"></i>提交报工
    </button>
    
    <a href="{:url('index/worker/index')}" class="block w-full text-center bg-gray-500 text-white py-2 rounded font-bold hover:bg-gray-600">
      <i class="fa fa-home mr-2"></i>返回首页
    </a>
  </form>
</div>

<script>
$(document).ready(function() {
    // 订单选择变化事件
    $('#order-select').on('change', function() {
        var orderId = $(this).val();
        if (orderId) {
            loadOrderModels(orderId);
        } else {
            $('#order-model-select').html('<option value="">请先选择订单</option>');
            $('#order-info').hide();
        }
    });
    
    // 产品型号和工序选择变化事件
    $('#order-model-select').on('change', function() {
        var selectedValue = $(this).val();
        if (selectedValue) {
            var selectedOption = $(this).find('option:selected');
            var piecePrice = parseFloat(selectedOption.data('piece-price'));
            var timePrice = parseFloat(selectedOption.data('time-price'));
            var orderQuantity = parseInt(selectedOption.data('order-quantity'));
            
            // 显示价格信息
            $('#piece-price').text(piecePrice.toFixed(2));
            $('#time-price').text(timePrice.toFixed(2));
            $('#price-info').show();
            
            // 更新最大可报工数量（使用订单数量作为参考）
            $('#max-quantity').text(orderQuantity);
            $('#quantity-input').attr('max', orderQuantity);
            
            // 显示订单信息
            $('#total-quantity').text(orderQuantity);
            $('#allocated-quantity').text('0');
            $('#available-quantity').text(orderQuantity);
            $('#order-info').show();
        } else {
            $('#price-info').hide();
            $('#order-info').hide();
        }
    });
    
    // 报工类型切换
    $('input[name="report_type"]').on('change', function() {
        var type = $(this).val();
        if (type === 'piece') {
            $('#piece-section').show();
            $('#time-section').hide();
            $('#time-range-section').hide();
        } else {
            $('#piece-section').hide();
            $('#time-section').show();
            $('#time-range-section').show();
        }
    });
    
    // 时间计算
    $('#start-time, #end-time').on('change', function() {
        calculateWorkHours();
    });
    
    // 表单提交
    $('#activeReportForm').on('submit', function(e) {
        e.preventDefault();
        submitActiveReport();
    });
});

// 加载订单的产品型号和工序
function loadOrderModels(orderId) {
    $.ajax({
        url: '/index/worker/getOrderModels',
        method: 'GET',
        data: { order_id: orderId },
        success: function(response) {
            if (response.code === 1) {
                var options = '<option value="">请选择产品型号和工序</option>';
                response.data.forEach(function(item) {
                    var displayText = item.display_name + ' - 订单数量:' + item.order_quantity;
                    options += '<option value="' + item.model_id + ':' + item.process_id + '" ' +
                              'data-piece-price="' + item.piece_price + '" ' +
                              'data-time-price="' + item.time_price + '" ' +
                              'data-order-quantity="' + item.order_quantity + '">' + displayText + '</option>';
                });
                $('#order-model-select').html(options);
            } else {
                alert(response.msg || '加载产品型号失败');
            }
        },
        error: function() {
            alert('网络错误，请重试');
        }
    });
}

// 计算工作时长
function calculateWorkHours() {
    var startTime = $('#start-time').val();
    var endTime = $('#end-time').val();
    
    if (startTime && endTime) {
        var start = new Date('2000-01-01 ' + startTime);
        var end = new Date('2000-01-01 ' + endTime);
        
        if (end > start) {
            var diffHours = (end - start) / (1000 * 60 * 60);
            $('#calculated-hours').text(diffHours.toFixed(2));
            $('#work-hours-input').val(diffHours.toFixed(2));
            $('#time-calculator').show();
        } else {
            $('#time-calculator').hide();
            alert('结束时间必须晚于开始时间');
        }
    } else {
        $('#time-calculator').hide();
    }
}

// 提交主动报工
function submitActiveReport() {
    var formData = new FormData($('#activeReportForm')[0]);
    var btn = $('#activeReportForm button[type=submit]');
    var originalText = btn.html();
    
    btn.html('<i class="fa fa-spinner fa-spin"></i> 提交中...').prop('disabled', true);
    
    $.ajax({
        url: window.location.href,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.code === 1) {
                alert('报工提交成功！');
                setTimeout(function() {
                    window.location.href = '/index/worker/index';
                }, 1500);
            } else {
                alert(response.msg || '提交失败');
                btn.html(originalText).prop('disabled', false);
            }
        },
        error: function() {
            alert('网络错误，请重试');
            btn.html(originalText).prop('disabled', false);
        }
    });
}
</script>
{include file="common/footer"} 